/**
 * creator:WhiteBird
 * create time:2016/10/20
 * email:zhiqiang.zhao@dhc.com.cn
 **/

#import "WhiteBirdPluginUP.h"
#import <Cordova/CDV.h>
#import "UMessage.h"
#import <UserNotifications/UserNotifications.h>

@interface WhiteBirdPluginUP ()<UNUserNotificationCenterDelegate>

@end

@implementation WhiteBirdPluginUP{
   NSString *methodId;
}
/*
 * 插件初始化自动执行方法
 */
- (void)pluginInitialize
{
    NSLog(@"WhiteBirdUP--->推送插件初始化");
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(applicationDidFinishLaunching:) name:UIApplicationDidFinishLaunchingNotification object:nil];

    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(receive:) name:@"PUSHKEY" object:nil];
}
/*
 * 友盟初始化配置
 */
- (void)applicationDidFinishLaunching:(NSNotification *)notification
{
    NSDictionary *settings = [self.commandDelegate settings];
    NSString *umengAppId = [settings objectForKey:@"wbp_umeng_appid"];
    NSLog(@"WhiteBirdUP--->wbp_umeng_appid:%@",umengAppId);
    NSDictionary *launchOptions = [notification userInfo];
    [UMessage startWithAppkey:umengAppId launchOptions:launchOptions];

    //注册通知。
    [UMessage registerForRemoteNotifications];
    //iOS10必须加下面这段代码。
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    center.delegate=self;
    UNAuthorizationOptions types10=UNAuthorizationOptionBadge|UNAuthorizationOptionAlert|UNAuthorizationOptionSound;
    [center requestAuthorizationWithOptions:types10     completionHandler:^(BOOL granted, NSError * _Nullable error) {
        if (granted) {
            NSLog(@"WhiteBirdUP--->RequestAuthorization success");
        } else {
            NSLog(@"WhiteBirdUP--->RequestAuthorization fail");
        }
    }];
    //打开日志，方便调试
    [UMessage setLogEnabled:YES];
}
/*
 * 添加标签
 */
- (void)addTag:(CDVInvokedUrlCommand *)command
{
    NSArray *arguments = [command arguments];
    if ([arguments count] != 1)
    {
        [self failWithCallbackId:command.callbackId withMessage:@"参数错误"];
        return;
    }

    [UMessage addTag:[arguments objectAtIndex:0]
            response:^(id responseObject, NSInteger remain, NSError *error) {
                if (responseObject)
                {
                    [self successWithCallbackId:command.callbackId withMessage:@"添加成功"];
                }
                else
                {
                    [self failWithCallbackId:command.callbackId withError:error];
                }
            }];
}
/*
 * 移除标签
 */
- (void)removeTag:(CDVInvokedUrlCommand *)command
{
    NSArray *arguments = [command arguments];
    if ([arguments count] != 1)
    {
        [self failWithCallbackId:command.callbackId withMessage:@"参数错误"];
        return;
    }

    [UMessage removeTag:[arguments objectAtIndex:0]
               response:^(id responseObject, NSInteger remain, NSError *error) {
                   if (responseObject)
                   {
                       [self successWithCallbackId:command.callbackId withMessage:@"移除成功"];
                   }
                   else
                   {
                       [self failWithCallbackId:command.callbackId withError:error];
                   }
               }];
}
/*
 * 获取标签
 */
- (void)getTags:(CDVInvokedUrlCommand *)command
{
    [UMessage getTags:^(NSSet *responseTags, NSInteger remain, NSError *error) {
        if (responseTags)
        {
            CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK
                                                               messageAsArray:[responseTags allObjects]];
            [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
        }
        else
        {
            [self failWithCallbackId:command.callbackId withError:error];
        }
    }];
}
/*
 * 移除所有标签
 */
- (void)removeAllTags:(CDVInvokedUrlCommand *)command
{
    [UMessage removeAllTags:^(id responseObject, NSInteger remain, NSError *error) {
        if (responseObject)
        {
            [self successWithCallbackId:command.callbackId withMessage:@"重置成功"];
        }
        else
        {
            [self failWithCallbackId:command.callbackId withError:error];
        }
    }];
}
/*
 * 添加别名
 */
- (void)addAlias:(CDVInvokedUrlCommand *)command
{
    NSArray *arguments = [command arguments];
    if ([arguments count] != 2)
    {
        [self failWithCallbackId:command.callbackId withMessage:@"参数错误"];
        return;
    }

    [UMessage addAlias:[arguments objectAtIndex:0]
                  type:[self mapUMessageAliasType:[[arguments objectAtIndex:1] integerValue]]
              response:^(id responseObject, NSError *error) {
                  if (responseObject)
                  {
                      [self successWithCallbackId:command.callbackId withMessage:@"添加成功"];
                  }
                  else
                  {
                      [self failWithCallbackId:command.callbackId withError:error];
                  }
              }];
}
/*
 * 设置别名，将会覆盖旧的以添加的别名
 */
- (void)setAlias:(CDVInvokedUrlCommand *)command
{
    NSArray *arguments = [command arguments];
    if ([arguments count] != 2)
    {
        [self failWithCallbackId:command.callbackId withMessage:@"参数错误"];
        return;
    }

    [UMessage setAlias:[arguments objectAtIndex:0]
                  type:[self mapUMessageAliasType:[[arguments objectAtIndex:1] integerValue]]
              response:^(id responseObject, NSError *error) {
                  if (responseObject)
                  {
                      [self successWithCallbackId:command.callbackId withMessage:@"重新添加成功"];
                  }
                  else
                  {
                      [self failWithCallbackId:command.callbackId withError:error];
                  }
              }];
}
/*
 * 移除别名
 */
- (void)removeAlias:(CDVInvokedUrlCommand *)command
{
    NSArray *arguments = [command arguments];
    if ([arguments count] != 2)
    {
        [self failWithCallbackId:command.callbackId withMessage:@"参数错误"];
        return;
    }

    [UMessage removeAlias:[arguments objectAtIndex:0]
                     type:[self mapUMessageAliasType:[[arguments objectAtIndex:1] integerValue]]
                 response:^(id responseObject, NSError *error) {
                     if (responseObject)
                     {
                         [self successWithCallbackId:command.callbackId withMessage:@"删除成功"];
                     }
                     else
                     {
                         [self failWithCallbackId:command.callbackId withError:error];
                     }
                 }];
}
/*
 * 设置渠道
 */
- (void)setChannel:(CDVInvokedUrlCommand *)command
{
    NSArray *arguments = [command arguments];
    if ([arguments count] != 1)
    {
        [self failWithCallbackId:command.callbackId withMessage:@"参数错误"];
        return;
    }
    NSLog(@"WhiteBirdUP--->Set Channel:%@",[arguments objectAtIndex:0]);
    [UMessage setChannel:[arguments objectAtIndex:0]];
}
/*
 * 接受推送时,控制调取js方式
 */
- (void)getPushBack:(CDVInvokedUrlCommand *)command
{
    NSLog(@"WhiteBird--->接收推送信息回调启动");
    methodId = command.callbackId;
}

/*
 * Function Method
 */
- (void)successWithCallbackId:(NSString *)callbackId withMessage:(NSString *)message
{
    CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK
                                                      messageAsString:message];
    [self.commandDelegate sendPluginResult:pluginResult callbackId:callbackId];
}

- (void)failWithCallbackId:(NSString *)callbackId withMessage:(NSString *)message
{
    CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR
                                                      messageAsString:message];
    [self.commandDelegate sendPluginResult:pluginResult callbackId:callbackId];
}

- (void)failWithCallbackId:(NSString *)callbackId withError:(NSError *)error
{
    [self failWithCallbackId:callbackId withMessage:[error localizedDescription]];
}
- (NSString *)mapUMessageAliasType:(NSInteger)intType
{
    NSString* alias;
    switch(intType)
    {
        case 0:
            alias = kUMessageAliasTypeSina;
            break;
        case 1:
            alias = kUMessageAliasTypeTencent;
            break;
        case 2:
            alias = kUMessageAliasTypeQQ;
            break;
        case 3:
            alias = kUMessageAliasTypeWeiXin;
            break;
        case 4:
            alias = kUMessageAliasTypeBaidu;
            break;
        case 5:
            alias = kUMessageAliasTypeRenRen;
            break;
        case 6:
            alias = kUMessageAliasTypeKaixin;
            break;
        case 7:
            alias = kUMessageAliasTypeDouban;
            break;
        case 8:
            alias = kUMessageAliasTypeFacebook;
            break;
        case 9:
            alias = kUMessageAliasTypeTwitter;
            break;
    }
    return alias;
}
- (void)receive:(NSNotification*)sender
{
    if(methodId)
    {
        NSLog(@"WhiteBird--->通知触发回调方法");

        CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK
                                                      messageAsDictionary:sender.object];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:methodId];
    }
}
@end
